<template>
  <div class="refine_ucreate">
    <h2 class="titleblue">{{title}}用户</h2>
    <div class="contant">
      <el-form :model="form" :rules="rules" ref="form" label-width="80px">
        <el-row>
          <el-col :span="12">
            <div class="grid-content ">
              <el-row>
                <el-col :span="24">
                  <div class="grid-content">
                    <el-form-item label="用户名" prop="username">
                      <el-input placeholder="新建账号用户名" :disabled="userDisable" v-model="form.username" class="select-width-220"
                                :readonly='editMode'></el-input>
                    </el-form-item>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <div class="grid-content">
                    <el-form-item label="证书类型" prop="certificate_type">
                      <el-select clearable v-model="form.certificateType" :disabled="userDisable" class="select-width-220"
                                 placeholder="请选择证书类型">
                        <el-option v-for="item in typeOptions" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                      </el-select>

                    </el-form-item>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <div class="grid-content">
                    <el-form-item label="证书等级" prop="certificate_level">
                      <el-select clearable v-model="form.certificateLevel" :disabled="userDisable" class="select-width-220"
                                 placeholder="请选择证书等级">
                        <el-option v-for="item in gradeOptions" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>

                      </el-select>
                    </el-form-item>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <div class="grid-content">
                    <el-form-item label="上传附件">
                      <el-upload class="upload-demo" :action="$config.FILE_UPLOAD_URL" :data='uploadModel'
                                 accept='.png,.jpg,.jpeg' :on-preview="handlePreview" :file-list="fileList"
                                 :on-remove="handleRemove" :limit="1" :before-upload="beforeAvatarUpload" :disabled="userDisable"
                                 :on-exceed="handleExceed" :on-success='uploadSuccess' :headers="headers">
                        <el-button size="small" type="primary">上传</el-button>
                        <div slot="tip" class="el-upload__tip">上传附件</div>
                      </el-upload>
                    </el-form-item>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <div class="grid-content">
                    <el-form-item label="执法证号" prop="certificate_number">
                      <el-input placeholder="执法证号" :disabled="userDisable" v-model="form.certificateNumber"
                                class="select-width-220"></el-input>
                    </el-form-item>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <div class="grid-content">
                    <el-form-item label="姓名" prop="fullname">
                      <el-input placeholder="新建账号使用者姓名" :disabled="userDisable" v-model="form.fullname" class="select-width-220"></el-input>
                      <span class="tips">(创建执法人员建议必填)</span>
                    </el-form-item>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <div class="grid-content">
                    <el-form-item label="手机号" prop="telephone">
                      <el-input placeholder="新建账号的手机号" :disabled="userDisable" v-model="form.telephone" class="select-width-220"></el-input>
                    </el-form-item>
                  </div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <div class="grid-content">
                    <el-form-item label="用户等级" prop="level">
                      <el-select clearable v-model="form.level" :disabled="userDisable" class="select-width-220 fl" placeholder="请选择用户等级">
                        <el-option label="普通员工" :value="0"></el-option>
                        <el-option label="科领导" :value="1"></el-option>
                        <el-option label="处领导" :value="2"></el-option>
                        <el-option label="市局领导" :value="3"></el-option>
                        <el-option label="省局领导" :value="4"></el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                </el-col>
              </el-row>
              <el-col v-if='$profile.olevel === 0'>
                <div class="grid-content">
                  <el-form-item label="指挥中心" prop="controlCenter">
                    <el-checkbox v-model="controlCenter" :disabled="userDisable" @change='switchControlCenter'>是</el-checkbox>
                  </el-form-item>
                </div>
              </el-col>

            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content">
              <div class="upload-img">
                <el-upload class="avatar-uploader" :action="$config.FILE_UPLOAD_URL" :data='uploadModel'
                           accept='.png,.jpg,.jpeg' :show-file-list="false" :disabled="userDisable"
                           :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="headers">
                  <img v-if="form.avatar" :src="form.avatar" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <p>个人照片</p>
              </div>

              <div class="user-div">
                <el-form-item label="用户权限" prop="roleId">
                  <el-checkbox-group v-model="form.roleId">
                    <el-checkbox v-for="(item,index) in roleList" :disabled="userDisable" :label="item.id" :key="index">{{item.name}}
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="grid-content">
              <el-form-item label="所属单位" prop="orgId">

                <el-input placeholder="" v-if="false" v-model="orgName" class="select-width-220 fl"
                          :disabled='true'></el-input>

<!--                <el-select clearable :disabled='controlCenter || $profile.olevel != 0 || userDisable' v-model="form.orgId"-->
                <el-select clearable v-model="form.orgId"
                           class="select-width-220 fl" style="margin-left:10px;" @change="changeOrg('')"
                           placeholder="单位名称选择">
                  <el-option v-for="item in orgArray" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>

                <el-select clearable :disabled='controlCenter' v-if="subOrgArray.length!=0" v-model="form.deptId"
                           class="select-width-220 fl" style="margin-left:10px;" placeholder="所属部门选择">
                  <el-option v-for="item in subOrgArray" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <!-- ------------------------ 新增角色等级 2019-8-01 By xiangpengfei ------------------------ -->
        <el-row>
          <el-col :span="24">
            <div class="grid-content">

            </div>
          </el-col>
        </el-row>
        <!-- ------------------------ 结束 ------------------------ -->
        <el-form-item class="footerbtn">
          <el-button @click="doCreate('form')" class="sure">提交</el-button>
          <el-button @click="doCancel('form')" class="cancel">取消</el-button>
        </el-form-item>
      </el-form>

    </div>
  </div>
</template>

<script>
  import dictService from '@/services/DictionaryService.js'
  import * as orgService from '@/services/OrganizationService.js'
  import * as sysUserService from '@/services/SysUserService.js'

  export default {
    props: ['roleArray', 'orgArray', 'userData', 'optionAdjust'],
    data: function () {
      return {
        form: {
          username: '',
          content: '',
          certificateType: '',
          certificateLevel: '',
          certificateNumber: '',
          fullname: '',
          telephone: '',
          orgId: '',
          deptId: '',
          roleId: [],
          userRoles: [],
          certificateFile: "",
          avatar: '',
          level: 0 // 用户等级
        },
        fileList: [],
        roleList: this.roleArray.filter(r => r.status === 0),
        title: "新建",
        controlCenter: false,
        editMode: false,
        typeOptions: [],
        gradeOptions: [],
        subOrgArray: [],
        userGroup: [],
        detail: '',
        rules: {
          username: [{required: true, type: "string", message: '请输入用户名'}, {
            pattern: /^[a-zA-Z0-9]+$/,
            message: '用户名不能输入汉字'
          }],
          // certificate_number: [{ required: true,message:'请输入执法证号'},{ min: 6, max: 6, message: '执法证号为6位', trigger: 'blur' }],
          fullname: [{required: true, message: '请输入姓名'}],
          telephone: [{required: true, message: '请输入手机号'}],
          level: [{required: true, message: '请选择用户等级', trigger: 'change'}],
          orgId: [{required: true, message: '请选择所属单位', trigger: 'change'}],
          roleId: [
            {type: 'array', required: true, message: '请至少选择一种用户角色', trigger: 'change'}
          ]
        },
        uploadModel: {
          filename: '',
          mimeType: "image/jpeg",
          bus: 'user'
          // appid: "135",
          // businessobj: "txt"
        },
        headers: {
          Authorization: 'Bearer ' + localStorage.getItem('token')
        },
        orgName: '',
        userDisable: false,
          orgArray1: []
      };
    },
    created() {
        if (this.optionAdjust) {
            this.userDisable = true
        }
      dictService.find('ZSDJ').then(data => {
        this.gradeOptions = data
      })

      dictService.find('ZSLX').then(data => {
        this.typeOptions = data
      })


      if (this.userData) {
        this.title = '编辑'
        this.editMode = true
        let user = this.userData
        this.form.telephone = user.telephone
        this.form.avatar = user.avatar
        this.form.certificateNumber = user.certificateNumber
        this.form.username = user.username
        this.form.fullname = user.fullname
        this.form.level = user.level
        this.form.roleId = user.userRoles ? user.userRoles.map(r => r.id) : []
        if (user.organiza.name === '指挥中心') {
          this.controlCenter = true
          this.switchControlCenter()
        } else if (user.organiza.level === 1) {
          this.form.orgId = user.organiza.id
          this.changeOrg()
        // } else if (user.organiza.level == 2) {
        //   this.form.orgId = user.organiza.parentId
          // this.form.deptId = user.organiza.id
          // this.changeOrg(user.organiza.id)
          // this.form.deptId = res.data.content.org.did
        } else {
          this.form.orgId = user.organiza.parentId
          this.changeOrg(user.organiza.id)
          // this.form.deptId = user.organiza.id
        }
        // this.form.deptId = res.data.content.user.deptId
        this.form.certificateLevel = user.certificateLevel
        this.form.certificateType = user.certificateType
        this.form.status = user.status
        this.form.jhiUserId = user.jhiUserId
        if (user.certificateFile && user.certificateFile.length) {
          this.fileList = user.certificateFile.split(',').map(item => {
            return {
              name: item.substring(item.lastIndexOf('user/') + 5, item.length),
              link: item
            }
          })
        }
      } else {
          orgService.findFlat().then(data => {
              if (this.$profile.organiza.level === 2) {
                  this.form.orgId = this.$profile.organiza.parentId
                  this.form.deptId = this.$profile.organiza.id
              } else if (this.$profile.organiza.level === 1) {
                  this.form.orgId = this.$profile.organiza.id
              }
              this.orgName = data.find(org => org.orgType === 0).name
          })
      }
    },
    methods: {
      switchControlCenter() {
        this.form.roleId = this.userData.userRoles ? this.userData.userRoles.map(r => r.id) : []
        if (this.controlCenter) {
          this.roleList = this.roleArray.filter(r => r.status === -1)
        } else {
          this.roleList = this.roleArray.filter(r => r.status === 0)
        }
      },
      changeOrg(deptId = '') {
        this.form.deptId = deptId
        if (!this.form.orgId) {
          this.subOrgArray = []
        } else {
          let org = this.orgArray.find(o => o.id === this.form.orgId)
            if (org) {
                this.subOrgArray = org.sub || []
            }
        }
      },

      handleRemove(file, fileList) {
      },
      handlePreview(file) {
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },

      handleAvatarSuccess(res) {
        this.form.avatar = res.data.link
      },
      beforeAvatarUpload(file) {
        this.uploadModel.filename = file.name
        return true;
      },
      uploadSuccess(res) {
        this.form.certificateFile = res.data.link
      },
      doCreate(formName) {
        if (this.form.roleId.length == 0) {
          this.$alert('请选择至少一种角色');
          return false;
        }
        this.$refs[formName].validate((valid) => {
          if (!valid) {
            return false
          }
          this.form.organiza = {id: this.form.deptId || this.form.orgId}
          this.form.userRoles = this.form.roleId.map(r => {
            return {id: r}
          })
          if (this.controlCenter) {
            this.form.organiza.id = 44
          }

          if (this.editMode) {
            this.form.id = this.userData.id
            // this.form.organiza = this.userData.organiza
            this.form.jhiUserId = this.userData.jhiUserId
            this.form.status = this.userData.status
            sysUserService.update(this.form).then(resp => {
              this.$alert('修改成功', {
                confirmButtonText: '确定',
                callback: action => {
                  this.$emit('close');
                }
              })
            })
          } else {
            sysUserService.create(this.form).then(resp => {
              this.$alert('添加成功', {
                confirmButtonText: '确定',
                callback: action => {
                  this.form.roleId = []
                  this.$refs[formName].resetFields();
                  // if (this.$route.path.lastIndexOf('userlist') != -1) {
                  this.$emit('close');

                }
              })
            })
          }
        });

      },
      doCancel(formName) {
        this.$refs[formName].resetFields();
        this.$emit('close');
      }
    }
  };

</script>

<style lang="scss">

  .refine_ucreate {
    width: 100%;
    display: inline-block;
    .upload-demo {
      width: 290px;
    }
    .el-upload--text {
      float: right;
      width: 58px;
      height: 40px;
      border: none;
      border-radius: 2px;
      margin-left: 5px;

      button {
        background-color: #0062cd;
        border-radius: 2px;
        border: none;
        padding: 0;
        width: 58px;
        height: 40px;

      }
    }

    .el-upload__tip {
      width: 220px;
      height: 40px;
      border-radius: 2px;
      border: solid 1px #dddddd;
      float: left;
      margin-top: 0;
      padding: 0 15px;
      font-size: 14px;
      color: #b9b9b9;
      text-align: left;
    }
    .el-upload-list__item.is-success .el-upload-list__item-status-label {
      display: block;
    }
    .tips {
      font-size: 12px;
      color: #999999;
      line-height: 40px;
      margin-left: 10px;
    }
    .upload-img {
      text-align: center;
      width: 100%;
      height: 150px;
    }
    .upload-img p {
      font-size: 14px;
      color: #666666;
    }
    .avatar-uploader {
      width: 100%;
      display: inline-flex;
    }
    .avatar-uploader .el-upload {
      border: solid 1px #c0bfbe;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      width: 86px;
      height: 120px;
      margin: 0 auto;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 35px;
      color: #aeaeae;
      width: 86px;
      height: 120px;
      line-height: 120px;
      text-align: center;
    }
    .avatar {
      width: 100%;
      height: 100%;
      display: block;
    }
    .user-div {
      width: 445px;
      height: 169px;
      margin-top: 100px;
    }
    .el-checkbox-group {
      width: 368px;
      height: 169px;
      border: solid 1px #dddddd;
      padding: 0px 15px;
      box-sizing: border-box;
      overflow-y: scroll;
    }
    .el-checkbox {
      margin-left: 0;
      width: 50%;
    }
    .footerbtn {
      text-align: center;
      margin-top: 88px;
    }
  }

</style>
